package info.thereisonlywe.core.essentials;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 
 * @author thereisonlywe
 */
public class TimeEssentials {

	public static double millisToYears(long m)
	{
		return m / (1000.0 * 60.0 * 60.0 * 24.0 * 365.26);
	}

	public static boolean inDST(String tz)
	{
		return inDST(tz, new Date());
	}

	public static boolean inDST(String tz, Date d)
	{
		return TimeZone.getTimeZone(tz).inDaylightTime(d);
	}

	public static double GMTOffset(String tz, Date d)
	{
		if (inDST(tz, d)) return rawGMTOffset(tz) + 1;
		else return rawGMTOffset(tz);
	}

	public static double GMTOffset(String tz)
	{
		if (inDST(tz)) return rawGMTOffset(tz) + 1;
		else return rawGMTOffset(tz);
	}

	public static double rawGMTOffset(String tz)
	{
		int rawOffset = TimeZone.getTimeZone(tz).getRawOffset();
		int hour = rawOffset / (60 * 60 * 1000);
		int minute = Math.abs(rawOffset / (60 * 1000)) % 60;
		double result = hour + (minute / 60.0);
		return result;
	}

	public static int getHour(String formattedTime)
	{
		StringBuilder sb = new StringBuilder();
		int count = 0;
		for (int i = 0; i < formattedTime.length(); i++)
		{
			char ch = formattedTime.charAt(i);
			if (Character.isDigit(ch))
			{
				count++;
				sb.append(ch);
				if (count == 2) return Integer.parseInt(sb.toString());
			}
		}
		return -1;
	}

	public static int getMinute(String formattedTime)
	{
		StringBuilder sb = new StringBuilder();
		int count = 0;
		int index = formattedTime.indexOf(':');
		for (int i = index + 1; i < formattedTime.length(); i++)
		{
			char ch = formattedTime.charAt(i);
			if (Character.isDigit(ch))
			{
				count++;
				sb.append(ch);
				if (count == 2) return Integer.parseInt(sb.toString());
			}
		}
		return -1;
	}

	public static int getMinuteOffset(String baseT, String t)
	{
		return (getMinute(t) - getMinute(baseT));
	}

	public static int getHourOffset(String baseT, String t)
	{
		return (getHour(t) - getHour(baseT));
	}

	public static int getTimeDifferenceInMinutes(String baseT, String t)
	{
		int hour = getHourOffset(baseT, t);
		if (hour < 0) hour += 12;
		int minute = getMinuteOffset(baseT, t);
		if (minute < 0)
		{
			minute += 60;
			hour--;
		}
		return hour * 60 + minute;
	}

	public static String getCurrentTime()
	{
		Calendar c = Calendar.getInstance();
		// return formatTime(c.get(Calendar.HOUR_OF_DAY),
		// Calendar.MINUTE, Calendar.SECOND);
		return new SimpleDateFormat("hh:mm:ss").format(c.getTime());
	}

	public static String formatTime(int hour, int minute, int second)
	{
		String result = "";
		if (hour < 10) result += "0";
		result += hour + ":";
		if (minute < 10) result += "0";
		result += minute + ":";
		if (second < 10) result += "0";
		result += second;
		return result;
	}
}
